package com.server.core.util;

import com.server.core.anno.Controller;
import com.server.core.anno.RequestMapping;
import com.server.core.config.BasicConfig;
import com.server.core.action.AbstractAction;
import com.server.core.domain.Trie;

import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 注册，查找action
 */
public class ActionUtil {

    public static String path = BasicConfig.path;
    public static String packagePath = BasicConfig.packagePath;
    public static List<Class> classes = new ArrayList<>();
    public static List<String> classeFilePath = new ArrayList<>();
    public static Map<String, Trie> ActionMap = new HashMap<>();
    private static PackageScanUtil scanner = PackageScanUtil.getInstance();

    /*
     包扫描
     */
    public static void packageScan(String dir) {
        classes = scanner.packageScan(dir, AbstractAction.class);
    }

    /*
       根据所有的action的类，按照Method分类
     */
    public static void setActionMap() {
        System.err.println("正在扫描action");
        classes.forEach(e -> {
            System.out.println("扫描" + e.getName());
            Controller controller = (Controller) e.getAnnotation(Controller.class);

            Method[] methods = e.getMethods();
            for (Method method : methods) {

                RequestMapping mapping = method.getAnnotation(RequestMapping.class);
                if (mapping != null) {
                    if (ActionMap.get(mapping.method()) == null) {
                        ActionMap.put(mapping.method().name(), new Trie());
                    }
                    Trie trie = ActionMap.get(mapping.method().name());
                    System.out.println(method);
                    trie.insert(mapping.value(), method);
                }
            }
        });
    }

    public static Method getMethod(String method, String uri) throws Exception {
        return ActionMap.get(method).get(uri);
    }

    /*
      获取相应的Action
     */
    public static AbstractAction getAction(String method, String uri) throws Exception {
        return SingletonActionUtil.getAction(getMethod(method, uri).getDeclaringClass());
    }

    /*
        获取相应的Action
       */
    public static AbstractAction getAction(Method method) throws Exception {
        if (method == null) {
            return null;
        }
        return SingletonActionUtil.getAction(method.getDeclaringClass());
    }
}
